package com.talkyun.openx.validator.impl;

import com.talkyun.openx.validator.annotation.StringValidator;

import java.lang.annotation.Annotation;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringValidatorImpl extends AbstractValidator {

    @Override
    public String validate(Annotation ann, String argName, Object argVal) {
        return doValidate((StringValidator) ann, argName, (String) argVal);
    }

    private String doValidate(StringValidator sv, String name, String val) {
        if (sv.notNull() && val == null) {
            return "参数不能为空!";
        }
        if (sv.notBlank() && isBlank(val)) {
            return "参数不能为空!";
        }
        if (sv.minLen() != -1) {
            if (isBlank(val) || val.length() < sv.minLen()) {
                return "参数不足最小长度：" + sv.minLen() + "!";
            }
        }
        if (sv.maxLen() != -1) {
            if (!isBlank(val) && val.length() > sv.maxLen()) {
                return "参数超过最大长度：" + sv.maxLen() + "!";
            }
        }
        if (!isBlank(sv.scopeRegx())) {
            Pattern p = Pattern.compile(sv.scopeRegx());
            Matcher m = p.matcher(val);
            if (!m.matches()) {
                return "参数字符超出范围：" + sv.scopeRegx() + "!";
            }
        }
        return null;
    }
}